package com.zszq.ms.bigmodeltest.model.deepseek;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zszq.ms.bigmodeltest.entity.AiBigmodelConfig;
import com.zszq.ms.bigmodeltest.enums.BigModelEnum;
import com.zszq.ms.bigmodeltest.model.BaseModel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Collections;
import java.util.List;

@Service
public class DeepSeekService implements BaseModel {

    public Mono<String> call(String content, AiBigmodelConfig aiBigmodelConfig) {
        ChatRequest request = new ChatRequest();
        List<ChatRequest.Message> messages = Collections.singletonList(new ChatRequest.Message("user", content));
        request.setMessages(messages);
        WebClient deepSeekWebClient = WebClient.builder().baseUrl(aiBigmodelConfig.getUrl()).defaultHeader(
                "Authorization", "Bearer " + aiBigmodelConfig.getKey()).defaultHeader("Content-Type", "application" +
                "/json").build();
        return deepSeekWebClient.post().uri("/chat/completions").bodyValue(request).retrieve().bodyToMono(ChatResponse.class).map(response -> response.getChoices().get(0).getMessage().getContent());
    }

    @Override
    public String getModelCode() {
        return BigModelEnum.DEEPSEEK.getCode();
    }

    @Override
    public JSONObject resTransferJson(String content, AiBigmodelConfig aiBigmodelConfig) throws Exception {
        Mono<String> call = call(content, aiBigmodelConfig);
        JSONObject res = new JSONObject();
        // 解析返回结果
        String jsonResponse = call.toString();
        if (StringUtils.isNotEmpty(jsonResponse)) {
            int start = jsonResponse.indexOf("{");
            int end = jsonResponse.indexOf("}", start);
            if (start != -1 && end != -1) {
                String result = jsonResponse.substring(start, end + 1);
                res = JSON.parseObject(result);
            }
        }
        return res;
    }
}
